<template>
  <el-aside width="200px" v-loading="loading">
    <el-container>
      <el-header>
        <el-input v-model="searchValue" placeholder="请输入部门名称" clearable size="default"
                  prefix-icon="el-icon-search"></el-input>
      </el-header>
      <el-main class="no-padding">
        <el-tree class="menu" ref="treeRef" node-key="deptId" default-expand-all highlight-current current-node-key="id"
                 :data="treeList" :props="deptProps" :expand-on-click-node="false"
                 :filter-node-method="handleFilterNodeMethod" @node-click="handleNodeClick"></el-tree>
      </el-main>
    </el-container>
  </el-aside>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import deptApi from "@/api/system/dept";
import treeUtil from "@/utils/tree";

const emit = defineEmits(['nodeClick']);

const treeRef = ref(null);
// 部门遮罩层
const loading = ref(false);
// 搜索用的部门名称
const searchValue = ref("");
// 部门列表数据
const treeList = ref([]);
// 部门 props
const deptProps = {
  children: "children",
  label: "name"
};

const getDeptList = () => {
  loading.value = true;
  deptApi.lists.get({enabled: true}).then(response => {
    treeList.value = treeUtil.buildTree(response.data.list);
    loading.value = false;
  })
}

// 筛选节点
const handleFilterNodeMethod = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
}

const handleNodeClick = (data) => {
  emit("nodeClick", data);
}

onMounted(() => {
  getDeptList();
})

watch(() => searchValue.value, (value) => {
  treeRef.value.filter(value);
});
</script>

<style scoped lang="scss">
</style>
